package com.thero.core.command;

import com.thero.core.chess.Color;
import com.thero.core.chess.Player;
import com.thero.core.chess.Room;
import com.thero.core.command.cmd.MatchCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;


public class RivalMatcher {
	
	private static Logger logger = LoggerFactory.getLogger(RivalMatcher.class);

	private static Queue<MatchInformation> queue;

	public RivalMatcher(){
		queue = new ConcurrentLinkedQueue<>();
	}

	/**
	 * 玩家匹配工具。
	 * 玩家发出匹配请求后，去匹配队列取玩家，取到则匹配成功，否则将玩家加入匹配队列中。
	 * @param player 要匹配的玩家
	 * @return 匹配成功，则返回一个游戏房间，否则返回Null
	 */
	public Room match(MatchInformation player){
		int playerId = player.getPlayerId();

		MatchInformation one = queue.poll();
		if(one == null){
			queue.add(player);
			logger.debug("Put a player into match wait queue. player id = {}", playerId);
			return null;
		}else{
			Player black = new Player(one.getHome(), one.getPlayerId(), playerId, Color.black);
			Player white = new Player(player.getHome(), playerId, one.getPlayerId(), Color.white);
			Room room = new Room(black, white);
			logger.info("Player match succed. room id = {}, black id = {}, white id = {}", room.getId(), one.getPlayerId(), playerId);
			return room;
		}
	}
}
